const Router = require('koa-router')
const mongoose = require('mongoose')

let router = new Router()
router.get('/',async(ctx)=>{
  ctx.body = 'qwerindextyyuiop'
})

router.post('/register',async(ctx)=>{
  const User = mongoose.model('User')
  let newUser = new User(ctx.request.body)

  await newUser.save().then(()=>{
    ctx.body={
      code:200,
      message:"注册成功"
    }
  }).catch(err=>{
    ctx.body={
      code:500,
      message:err
    }
  })
})

router.post('/login',async(ctx)=>{
  let loginUser = ctx.request.body
  console.log(loginUser)
  let userName = loginUser.userName
  let password = loginUser.password

  //
  const User = mongoose.model('User')
  await User.findOne({userName:userName}).exec()
  .then(async(result)=>{
    console.log(result)
    // console.log(password,result.password,password==result.password)
    if(result){
      if(password == result.password){
        ctx.body={code:200,message:true}
      }else{
        ctx.body={code:200,message:false}
      }
    }else{
      ctx.body={code:200,message:'用户名不存在'}
    }
  }).catch(error=>{
    console.log(error)
    ctx.body={
      code:500,
      message:error
    }
  })

})

module.exports = router